// pages/personnel/index/home/index.js
import Config from "../../../../main.config";
import {getStorageSync, setStorage} from "../../../../utils/Storage";
import {getAlumniList, getStudentGrades} from "../../../../service/Student";
import {addFocus, delFocus} from "../../../../service/Collection";
import {exchangeContact, invitationDelivery, sendGZHTemplate} from "../../../../service/Message";
import Dialog from "@vant/weapp/dialog/dialog";
import {getList, getMajorList} from "../../../../service/Education";
Component({

    /*
    * 默认接收全局样式
    * */
    options: {
        addGlobalClass: true,
        styleIsolation: "shared"
    },

    /**
     * 组件的属性列表
     */
    properties: {

    },

    lifetimes: {
        attached: function () {
            let registerInfo = getStorageSync(Config.storage.registerInfo) || {};
            let storageSchool = getStorageSync(Config.storage.switchSchool) || {};
            this.data._registerInfo = registerInfo;
            this.data._search = {schoolNo: storageSchool.schoolNo || registerInfo.schoolNo};
            this.data._schoolName = storageSchool.schoolNo || registerInfo.schoolName;
            this.getStudentGrades();
            this.getEducationList();
            this.getMajorList();
            this.setData({"_alumni.loading": true});
            wx.setNavigationBarTitle({title: "校友(" + (storageSchool.schoolName || registerInfo.schoolName) + ")"})
        }
    },

    pageLifetimes: {
        show: function () {
            let schoolName = this.data._schoolName;
            wx.setNavigationBarTitle({title: "校友(" + schoolName + ")"})
        }
    },

    /**
     * 组件的初始数据
     */
    data: {
        //专业
        _major: {
            list: [
                {text: "全部专业", value: 0 }
            ],
            current: 0
        },
        //年级
        _years: {
            list: [
                { text: "全部年级", value: 0 }
            ],
            current: 0
        },
        _educationAction: {
            show: false,
            actions: []
        },
        //招聘信息
        _alumni: {
            loading: false,
            reset: false,
            error: false,
            total: -1,
            list: []
        },

    },

    /**
     * 组件的方法列表
     */
    methods: {

        /*
        * 获取专业列表
        * */
        getMajorList: async function () {
            try {
                let schoolNo = this.data._search.schoolNo || "";
                let res = await getMajorList(schoolNo);
                let list = [{text: "全部专业", value: 0 }];
                if (res.length === 0) return false;
                let newList = res.map(function (item, index) {
                    return {
                        text: item.professionalName,
                        value: index + 1,
                        no: item.professionalNo
                    }
                })
                this.setData({
                    "_major.list": list.concat(newList)
                })
            } catch (e) {
                console.error(e)
            }
        },

        /*
        * 获取第几届列表
        * */
        getStudentGrades: async function () {
            try {
                let res = await getStudentGrades();
                let list = [{ text: "全部年级", value: 0 }];
                if (res.length === 0) return false;
                let newList = res.map(function (item, index) {
                    return {
                        text: item,
                        value: index + 1
                    }
                })
                this.setData({
                    "_years.list": list.concat(newList)
                })
            } catch (e) {
                console.error(e)
            }
        },

        /*
        * 获取受教育列表
        * */
        getEducationList: async function () {
            try {
                let userId = this.data._registerInfo.createUser;
                let list = await await getList(userId);
                list.length > 0 ? this.setData({
                    "_educationAction.actions": list.map(function (item) {
                        return {
                            name: item.schoolName,
                            schoolNo: item.schoolNo
                        }
                    })
                }) : null
            } catch (e) {
                console.error(e)
            }
        },
        /*
        * 列表加载
        * */
        onLoadList: async function (e) {
            try {
                let search = this.data._search;
                let paging = e.detail.paging;
                let list = this.data._alumni.list;
                let isReset = this.data._alumni.reset;
                let postData = Object.assign(search, {
                    page: paging.page,
                    limit: paging.pageSize,
                })
                let res = await getAlumniList(postData);
                let newList = res.data.map(function (item) {
                    let logUrl = Config.api.downLoad + "?fileId=" + item.logo;
                    return {
                        id: item.id,
                        logo: logUrl,
                        name: item.name,
                        sex: item.sex,
                        schoolName: item.schoolName,
                        professionalName: item.professionalName,
                        grade: item.grade.split(";")[1].substr(0, 4),
                        strings: item.stringList.join(","),
                        createUser: item.createUser,
                        contact: item.contact,
                        focus: item.focus,
                        yqCount: item.yqCount,
                        eventId: item.eventId || 0
                    }
                });
                list = isReset ? newList : list.concat(newList);
                this.setData({
                    "_alumni.list": list,
                    "_alumni.total": res.count
                });
            } catch (e) {
                console.log(e)
                this.setData({
                    "_alumni.error": true
                })
            } finally {
                this.setData({
                    "_alumni.reset": false,
                    "_alumni.loading": false
                })
            }
        },

        /*
        * 监听menu切换
        * */
        onMenuChange: function (e) {
            let name = e.currentTarget.dataset.name;
            let index = e.detail;
            let current = this.data[name].current;
            if (index === current) return false;
            let search = this.data._search;
            let list = this.data[name].list;
            let currentData = list[index];
            switch (name) {
                case "_major":
                    currentData.no ? search.professionalNo = currentData.no : delete search.professionalNo
                    break
                case "_years":
                    index > 0 ? search.grade = currentData.text : delete search.grade
                    break
                default:
                    break
            }
            this.setData({
                [name + ".current"]: index,
                "_alumni.reset": true
            })
        },

        /*
        * 切换学校
        * */
        bindSchoolChange: function () {
            this.setData({"_educationAction.show": true});
        },
        onActionClose: function () {
            this.setData({"_educationAction.show": false})
        },
        onActionSelect: function (e) {
            let search = this.data._search;
            let {name, schoolNo} = e.detail
            if (search.schoolNo !== schoolNo) {
                this.data._search.schoolNo = schoolNo;
                this.data._schoolName = name;
                this.getMajorList();
                this.setData({"_alumni.reset": true});
                setStorage(Config.storage.switchSchool, {schoolNo: schoolNo, schoolName: name})
                wx.setNavigationBarTitle({title: "校友(" + name + ")"})
            }
        },

        /*
        * 点击按钮
        * */
        bindClickButton: async function (e) {
            let registerInfo = this.data._registerInfo;
            let index = e.currentTarget.dataset.index;
            let name = e.currentTarget.dataset.name;
            try {
                let list = this.data._alumni.list;
                let id = list[index].id;
                let toUserId = list[index].createUser;
                this.setData({["_alumni.list[" + index + "]." + name + "Loading"]: true});
                switch (name) {
                    case "gz": //关注
                        let focus = this.data._alumni.list[index].focus;
                        focus < 1 ? await addFocus({
                            userId: registerInfo.id,
                            objectId: id
                        }) : await delFocus({
                            userId: registerInfo.id,
                            objectId: id
                        })
                        this.setData({["_alumni.list[" + index + "].focus"]: focus < 1 ? 1 : 0});
                        focus < 1 ? await sendGZHTemplate({
                            userId: toUserId,
                            pagepath: "/pages/index/index?active=1",
                            type: 1
                        }) : null
                        break
                    case "jhlxfs": //交互联系方式
                        let contact = this.data._alumni.list[index].contact;
                        if (contact > 0) {
                            await Dialog.alert({
                                title: "提示",
                                message: "交换联系方式每天只能申请一次",
                                selector: "#van-personnel-dialog",
                                context: this
                            })
                            return false
                        }
                        await exchangeContact({
                            messageUserid: id,
                            message: registerInfo.phone,
                            sendUserid: registerInfo.id
                        })
                        this.setData({
                            ["_alumni.list[" + index + "].contact"]: 1,
                            ["_alumni.list[" + index + "].eventId"]: 0
                        });
                        await sendGZHTemplate({
                            userId: toUserId,
                            pagepath: "/pages/index/index?active=1",
                            type: 2
                        })
                        break
                    case "yqtd": //邀请投递
                        let yqCount = this.data._alumni.list[index].yqCount;
                        if (yqCount > 0) {
                            await Dialog.alert({
                                title: "提示",
                                message: "每天只能邀请一次投递信息",
                                selector: "#van-personnel-dialog",
                                context: this
                            })
                            return false
                        }
                        await invitationDelivery({
                            messageUserid: id,
                            eventid: registerInfo.id
                        })
                        this.setData({["_alumni.list[" + index + "].yqCount"]: 1});
                        await Dialog.alert({
                            title: "提示",
                            message: "已经发送邀请投递信息；请在【消息】栏目里查收",
                            selector: "#van-personnel-dialog",
                            context: this
                        })
                        await sendGZHTemplate({
                            userId: toUserId,
                            pagepath: "/pages/index/index?active=1",
                            type: 3
                        })
                        break
                }
            } catch (e) {
                console.error(e)
            } finally {
                this.setData({["_alumni.list[" + index + "]." + name + "Loading"]: false});
            }

        }
    }
})
